<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>code 2 jsdoc @example</title>
    <style>
      body {
        font-family: Arial;
      }
      textarea {
        font-family: Courier, monospace;
        border: 1px solid #ccc;
        border-radius: 4px;
        margin: 0.5rem;
        padding: 0.5rem;
        font-size: medium;
      }
    </style>
  </head>
  <body>
    <center>
      <h1>code 2 jsdoc @example</h1>
      <p>
        Given an example pasted in the left textarea, will generate a result
        ready to be pasted into a JSDoc comment.
      </p>
      <div id="app">
        <textarea
          id="code"
          cols="80"
          rows="40"
          onkeyup="document.getElementById('comment').value = t(this.value)"
        ></textarea>
        <textarea id="comment" cols="80" rows="40" style="color: green">
        </textarea>
      </div>
    </center>
    <script>
      const code = document.getElementById("code")
      const comment = document.getElementById("comment")

      function t(src) {
        // Replace multiline comments with lines prefixed by '// ' and preserve indentation
        const withoutMultilineComments = src.replace(
          /\/\*([\s\S]*?)\*\//g,
          (_, content) => {
            const commentLines = content
              .split("\n")
              .filter((line) => line.trim() !== "")
            return commentLines
              .map((line) => {
                const trimmedLine = line.replace(/^\s*\*/, "").trim()
                const indent = line.match(/^\s*/)[0]
                return `// ${indent}${trimmedLine}`
              })
              .join("\n")
          }
        )

        const lines = withoutMultilineComments
          .split("\n")
          .map((line) => " * " + line)
        return (
          " *\n * @example\n * ```ts\n" + lines.join("\n") + "\n * ```\n *\n"
        )
      }
    </script>
  </body>
</html>
